<?php

namespace App\Console\Commands;

use App\Constant\NewFlowEnum;
use App\Constant\QueueKey;
use App\Events\NewFlowOrderEvent;
use App\Events\UserLoanApplyEvent;
use App\Facades\MoneyPlatformRequestFacade;
use App\Jobs\GetLoanResultJobQueue;
use App\Library\Tools\ExcelExport;
use App\Mail\LoanMail;
use App\Models\LoanApply;
use App\Models\SettingRepayRate;
use App\Models\User;
use App\Models\UserCertOcr;
use App\Models\UserGlobal;
use App\Models\UserLoanRequest;
use App\Models\UserSyncInfo;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;

class SendFmail extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send_f_mail:cron {action : sendmail|usermoneyfail|updateloanapply}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'send mail to us';


    /**
     * F13 客服邮件
     * @var string
     */
    private $_checkBill_1 = ['liusong<liusong@weishangtech.com>'];

    /**
     * Create a new command instance.
     *
     * @return void
     */


    public function __construct()
    {
        parent::__construct();
    }

    /**
     * The console command action. month|common|money|help
     *
     * @var string
     */
    protected $action;

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->initAction();
        $this->runAction();
    }


    /**
     * Description: Initialize command action.
     * Author: Gxs
     */
    protected function initAction()
    {
        $this->action = $this->argument('action');

        if (!in_array($this->action, ['sendmail', 'usermoneyfail', 'updateloanapply'])) {
            $this->error("Invalid argument '{$this->action}'. Expected .");
            exit(1);
        }
    }

    /**
     * Description: Run action.
     * Author: Gxs
     */
    protected function runAction()
    {
        $this->{$this->action}();
    }


    /**
     * Description : 上午9点发送邮件 F13 提现失败的
     * Author ： szg
     * Date : 20190409 15:55
     * @throws \App\Exceptions\GeneralException
     */

    public function sendmail()
    {
        try {
            $Fres = LoanApply::where(['sub_code' => 'F13'])->get();
            $data = [];
            $i = 0;
            foreach ($Fres as $item) {
                if (!empty($item->trans_money_list)) {
                    foreach ($item->trans_money_list as $item2) {
                        if ($item2['transType'] == 03 && $item2['transStatus'] == 'F') {
                            $i++;
                            //这里面就是 F13 并且 提现失败的人

                            $peores = User::where(['id' => $item->user_id])->first();
                            if ($peores) {
                                $data[$i]['phonenum'] = $peores->phone_num;
                            }

                            $nameres = UserCertOcr::where(['user_id' => $item->user_id])->first();
                            if ($nameres) {
                                $data[$i]['name'] = $nameres->name;
                            }
                            $data[$i]['id'] = $item->user_id;

                        }
                    }

                }
            }

            $date = Carbon::now();

            if (empty($data)) {
                throw new \Exception(Carbon::now() . '无数据');
            }

            $header = [
                '电话号码',
                '用户姓名',
                '编号'
            ];
            $fields = [
                'phonenum',
                'name',
                'id'
            ];

            $file = 'F13tixian' . $date . '.xlsx';
            $path = storage_path($file);
            $excel = new ExcelExport($data, $header, $fields, $file, $path);
            $excel->commandExport($path);
            Mail::to($this->_checkBill_1)->send(new LoanMail($path));
            $this->info('export loan data is ok!!!');
            Log::debug('今日F13邮件发送成功');
            unlink($path);
        } catch (\Exception $e) {
            Log::debug('今日F13邮件异常推送' . $e->getMessage());
            $this->info('今日F13邮件异常推送：' . $e->getMessage());
        }

    }

    /**
     * 晋商的用户放款不要处理  制为放款失败
     */
    public function usermoneyfail()
    {
        //'1439976' => 1449774 userid  => loan_request_id
        $user = [
            '1249984' => 1097029,
            '541961' => 1443402,
            '1258122' => 1468730,

            //'766764' => 1189755, //用户放款信息表 无
            //'1627149' => 1750557, //用户放款信息表 无
        ];
        try {
            foreach ($user as $k => $v) {

                $is_peo_have = User::where(['id' => $k])->first();
                if ($is_peo_have) {
                    $loanapps = LoanApply::where(['loan_request_id' => $v])->first();
                    if (!empty($loanapps)) {
                        LoanApply::where(['loan_request_id' => $v])->update([
                            'loan_status' => LoanApply::LOAN_STATUS_FAIL,
                            'sub_code' => 'F'
                        ]);
                    }
                    $userG = UserGlobal::where(['uid' => $k])->first();
                    if (!empty($userG)) {
                        UserGlobal::where(['uid' => $k])->update([
                            'global_status' => UserGlobal::STATUS_LOAN_MONEY_FAIL
                        ]);
                    }


                    echo 'success' . PHP_EOL;

                }
            }

        } catch (\Exception $e) {
            $this->info('程序异常：' . $e->getMessage());
        }

    }

    /**
     * Description : 修复loanapply 的 参数缺少 导致放款成功 业务没有更新的问题
     * @throws \App\Exceptions\GeneralException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function updateloanapply()
    {
        try {
                $loanidRes = [
                    '207028' => 'LO201903191050416709636989444980',
                    '207309' => 'LO201903191052530069577553635304',
                    '204476' => 'LO201903191041038389524127529422',
                    '1210297' => 'LO201904061402057799863069310735',
                ];

                foreach ($loanidRes as $k => $v) {
                    $res = MoneyPlatformRequestFacade::queryLoanResult($v);
                    //dd($res);
                    $pre_insurance_amt = UserLoanRequest::where(['id' => $k])->first();

                    //获取相关费率
                    $getReplyRate = SettingRepayRate::getRateByChannl($pre_insurance_amt->channel, $pre_insurance_amt->actually_period);
                    //dd($getReplyRate);
                    $lending_rate = $getReplyRate['lending_rate'];
                    $insurance_rate = $getReplyRate['insurance_rate'];
                    //$insure_rate = $getReplyRate['insure_rate'];
                    $month_insurance_rate = $getReplyRate['month_insurance_rate'];
                    $manage_rate = $getReplyRate['manage_rate'];
                    $repayment_rate = $getReplyRate['repayment_rate'];
                    $fines_rate = $getReplyRate['fines_rate'];
                    if (!empty($res)) {
                        LoanApply::where(['loan_request_id' => $k])->update([
                            'loan_id' => $res['data']['loanId'],
                            'sub_code' => 'P',
                            'loan_sign' => $res['sign'],
                            //'amount' => $res['amount'],
                            //'pre_insurance_amt' =>$pre_insurance_amt->pre_insurance_amt,
                            //'period' => $res['period'],
                            'out_trade_id' => $res['data']['outTradeId'],
                            'message' => $res['data']['message'],
                            'lending_rate' => $lending_rate,
                            'insurance_rate' => $insurance_rate,
                            'month_insurance_rate' => $month_insurance_rate,
                            'manage_rate' => $manage_rate,
                            'repayment_rate' => $repayment_rate,
                            'fines_rate' => $fines_rate,
                            'is_send_loan' => LoanApply::SEND_SMS,

                        ]);

                        $applies = LoanApply::where(['loan_request_id' => $k])->first();

                        //更新user_globals表用户流程状态事件
                        event(new UserLoanApplyEvent($applies));
                        if ($applies->loan_status == LoanApply::LOAN_STATUS_PROCESSING) {
                            //任务三分钟后加入队列处理，获取放款处理结果
                            // 99 置为放款中  如果$loan_id 为空  不进入队列
                            if (!empty($applies->loan_id)) {
                                echo 'jion queue success' . PHP_EOL;
                                GetLoanResultJobQueue::dispatch($applies)->onQueue(QueueKey::QUEUE_GET_LOAN_RESULT)->delay(Carbon::now()->addMinutes(3));
                            }

                        }


                        echo 'success' . PHP_EOL;
                    }
                }

            } catch (\Exception $e) {
            $this->info('程序异常：' . $e->getMessage());
        }

        /*$res = MoneyPlatformRequestFacade::queryLoanResult('LO201904061402057799863069310735');
        dd($res);*/
    }

}

























